import type { LineString } from 'geojson'
import { geometryOfArc, type LngLat } from '@/geom/great-circle'
import { addAuxGraphic, type AuxGraphic } from '../core'
import { keyGen } from '@/common'
import type { MapFeatures } from '@/map'
import { auxGraphicProperties } from '../core/base'

export interface AuxArc extends AuxGraphic {
  type: 'Arc'
  center: LngLat
  radius: number
  bearing1: number
  bearing2: number
}
const nameGen = keyGen('辅助圆弧#')

function nextName(): string {
  return nameGen.next()
}

export function addAuxArc(center: LngLat, radius: number, bearing1: number, bearing2: number) {
  addAuxGraphic<AuxArc>({
    type: 'Arc',
    name: nextName(),
    center,
    radius,
    bearing1,
    bearing2
  })
}

export function toLineString(ac: AuxArc): LineString {
  return geometryOfArc(ac.center, ac.radius, ac.bearing1, ac.bearing2, 40)
}

export function toFeature(ac: AuxArc, g: LineString[]): MapFeatures {
  const geometry = g.length > 0 ? g[0] : toLineString(ac)
  return {
    symbol: [
      {
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: geometry.coordinates[Math.floor(geometry.coordinates.length / 2)]
        },
        properties: auxGraphicProperties.symbol(ac.name)
      }
    ],
    line: [
      {
        type: 'Feature',
        geometry,
        properties: auxGraphicProperties.line
      }
    ]
  }
}
